package com.pai4j.common.util.community;

import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Iterator;

public class HtmlToMarkdownConverter {

    private static final FlexmarkHtmlConverter CONVERTER = FlexmarkHtmlConverter.builder().build();

    public static String convert(String html) {

        return CONVERTER.convert(html);
    }

//    public static String convertV2(String html) {
//
//        DataHolder options = PegdownOptionsAdapter.flexmarkOptions(
//                Extensions.ALL & ~Extensions.ANCHORLINKS // 禁用自动锚点
//        );
//        Parser parser = Parser.builder(options).build();
//        HtmlRenderer renderer = HtmlRenderer.builder(options).build();
//        return renderer.render(parser.parse(html));
//    }


    /**
     * html 清洗 + 转MD
     * @param html
     * @return
     */
//    public static String convertV3(String html) {
//
//        return convertV2(htmlETL(html));
//    }

    public static String htmlETL(String html) {
        // html 转 dom 树
        Document document = Jsoup.parse(html);
        deepHandleElem(document.children());
        return document.html();
    }

    public static void deepHandleElem(Elements elements) {
        if (elements == null || elements.isEmpty()) {
            return;
        }
        for (Element child : elements) {
            if (!child.tagName().equals("img")) {
                Attributes attributes = child.attributes();
                Iterator<Attribute> iterator = attributes.iterator();
                while (iterator.hasNext()) {
                    Attribute attribute = iterator.next();
                    String key = attribute.getKey();
                    child.removeAttr(key);
                }
            }
            deepHandleElem(child.children());
        }
    }
}